package top.stmo.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.stmo.blog.dao.dos.Archives;
import top.stmo.blog.dao.mapper.ArticleBodyMapper;
import top.stmo.blog.dao.mapper.ArticleMapper;
import top.stmo.blog.dao.mapper.ArticleTagMapper;
import top.stmo.blog.dao.pojo.Article;
import top.stmo.blog.dao.pojo.ArticleBody;
import top.stmo.blog.dao.pojo.ArticleTag;
import top.stmo.blog.dao.pojo.SysUser;
import top.stmo.blog.dao.vo.ArticleBodyVo;
import top.stmo.blog.dao.vo.ArticleVo;
import top.stmo.blog.dao.vo.Result;
import top.stmo.blog.dao.vo.TagVo;
import top.stmo.blog.dao.vo.params.ArticleParam;
import top.stmo.blog.dao.vo.params.PageParams;
import top.stmo.blog.service.*;
import top.stmo.blog.utils.UserThreadLocal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private TagService tagService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ArticleTagMapper articleTagMapper;


    /**
     *  加入归档文章列表筛选条件 重写之前的方法,Mybatis—Plus换成 Mybatis自己写sql语句
     */


    @Override
    public Result listArticle(PageParams pageParams) {
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        IPage<Article> articleIPage = articleMapper.listArticle(
                page,
                pageParams.getCategoryId(),
                pageParams.getTagId(),
                pageParams.getYear(),
                pageParams.getMonth());
        List<Article> records = articleIPage.getRecords();
        for(Article article : records) {
            System.out.println("===================");
            System.out.println(article);
            System.out.println("===================");
        }
        return Result.success(copyList(records,true,true));
    }


/**
    @Override
    public Result listArticle(PageParams pageParams) {

         // 1.分页查询article数据库表得到的结果

        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //进行文章分类判断
        if(pageParams.getCategoryId() != null) {
            queryWrapper.eq(Article::getCategoryId,pageParams.getCategoryId());
        }
        List<Long> articleIdList = new ArrayList<>();
        //进行文章标签列表判断
        if(pageParams.getTagId() != null) {
            //加入标签条件查询
            //article表中 并没有tag字段 一篇文章 有多个标签
            //article_tag article_id  一对多关系  tag_id
            LambdaQueryWrapper<ArticleTag> articleTagQueryWrapper = new LambdaQueryWrapper<>();
            articleTagQueryWrapper.eq(ArticleTag::getTagId,pageParams.getTagId());
            List<ArticleTag> articleTags = articleTagMapper.selectList(articleTagQueryWrapper);
            for(ArticleTag articleTag : articleTags) {
                articleIdList.add(articleTag.getArticleId());
            }
            if(articleIdList.size() > 0) {
                //  and id in(1,2,3)
                queryWrapper.in(Article::getId,articleIdList);
            }
        }

        //查询条件为置顶排序+创建时间逆序排列
        queryWrapper.orderByDesc(Article::getWeight,Article::getCreateDate);
        Page<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
        List<Article> records = articlePage.getRecords();
        //能直接返回嘛？很明显不能,则新建vo实体结果集和页面数据对应
        // 新建copyList方法将数据库结果集转换成页面所需结果集，即dao转换成vo
        List<ArticleVo> articleVoList = copyList(records,true,true);
        return Result.success(articleVoList);
    }
**/

    @Override
    public Result hotArticle(int limit) {
        /*
        用MybatisPlus写
        new一个LambdaQueryWrapper对象
        设置查询条件
        1.根据ViewCounts 倒序输出
        2.查询   Id,Title
        3.查询条数为  limit
        将LambdaQueryWrapper对象放入selectList

        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .orderByDesc(Article::getViewCounts)
                .select(Article::getId,Article::getTitle)
                .last("limit "+limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);
       */
        List<Article> articles = articleMapper.hotArticle(limit);
        return Result.success(copyList(articles,false,false));
    }

    @Override
    public Result newArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .orderByDesc(Article::getCreateDate)
                .select(Article::getId,Article::getTitle)
                .last("limit "+limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articles,false,false));
    }

    @Override
    public Result listArchives() {
        List<Archives> archivesList = articleMapper.listArchives();
        return Result.success(archivesList);
    }

    @Autowired
    private ThreadService threadService;

    @Override
    public Result findArticleById(Long articleId) {
        /**
         * 1.根据Id查询 文章信息
         * 2.根据bodyId和categoryid 去做关联查询
         */
        Article article = this.articleMapper.selectById(articleId);
        ArticleVo articleVo = copy(article, true, true,true,true);
        //查看完文章之后，新增阅读数，有没有问题？
        //查看完文章之后，本应该直接返回数据，这时做了一个更新操作，更新时加写锁，阻塞其他的读操作，性能就会比较低
        //更新增加了本次接口的耗时  一旦更新出现问题，不能影响查看文章的操作
        //线程池   可以把更新操作仍到线程池中去执行，和主线程就不相关了
        threadService.updateArticleViewCount(articleMapper,article);
        return Result.success(articleVo);
    }

    @Override
    public Result publish(ArticleParam articleParam) {
        /**
         *  1.发布文章  目的  构建article对象
         *  2.作者Id  当前登录用户  拿当前登录用户则用UserThreadLocal   用UserThreadLocal  则需要把此接口加入到登录拦截中
         *  3.标签    要将标签加入到 关联列表当中（需tagId和articleId）    tag通过参数获取   articleId通过插入生成
         *  4.body  内容存储表
         */
        //获取登录对象的信息
        SysUser sysUser = UserThreadLocal.get();
        //new一个文章对象
        Article article = new Article();
        //设置作者Id
        article.setAuthorId(sysUser.getId());
        article.setWeight(Article.Article_Common);
        article.setViewCounts(0);
        article.setTitle(articleParam.getTitle());
        article.setCreateDate(System.currentTimeMillis());
        article.setSummary(articleParam.getSummary());
        article.setCommentCounts(0);
        article.setCategoryId(Long.parseLong(articleParam.getCategory().getId()));
        //插入后生成一个文章Id
        this.articleMapper.insert(article);
        //从参数中获取Tags对象列表
        List<TagVo> tags = articleParam.getTags();
        if(tags != null) {
            //list列表 所有要循环
            for(TagVo tag : tags) {
                Long articleId = article.getId();
                ArticleTag articleTag = new ArticleTag();
                //将Id转换为long类型并存入TagId
                articleTag.setTagId(Long.parseLong(tag.getId()));
                articleTag.setArticleId(articleId);
                articleTagMapper.insert(articleTag);
            }
        }
        //body
        ArticleBody articleBody = new ArticleBody();
        articleBody.setArticleId(article.getId());
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBodyMapper.insert(articleBody);
        //给article设置BodyId的值
        article.setBodyId(articleBody.getId());
        articleMapper.updateById(article);
        Map<String,String> map = new HashMap<>();
        map.put("id",article.getId().toString());
        return Result.success(map);
    }

    @Autowired
    private CategoryService categoryService;

    //通过循环调用copy把整个List集合转换
    private List<ArticleVo> copyList(List<Article> records,boolean isTag,boolean isAuthor) {

        List<ArticleVo> articleVoList = new ArrayList<>();
        for(Article record : records) {
            articleVoList.add(copy(record,isTag,isAuthor,false,false));
        }
        return articleVoList;
    }

    private List<ArticleVo> copyList(List<Article> records,boolean isTag,boolean isAuthor,boolean isBody,boolean isCategory) {

        List<ArticleVo> articleVoList = new ArrayList<>();
        for(Article record : records) {
            articleVoList.add(copy(record,isTag,isAuthor,isBody,isCategory));
        }
        return articleVoList;
    }

    //转换一个Article对象的方法
    private ArticleVo copy(Article article,boolean isTag,boolean isAuthor,boolean isBody,boolean isCategory) {
        ArticleVo articleVo = new ArticleVo();
        //将Id设置转换为String类型
        articleVo.setId(String.valueOf(article.getId()));
        BeanUtils.copyProperties(article,articleVo);
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm"));
        //并不是所有的接口都需要标签，作者信息
        if(isTag) {
            Long articleId = article.getId();
            articleVo.setTags(tagService.findTagsByArticleId(articleId));
        }
        if(isAuthor) {
            Long authorId = article.getAuthorId();
            articleVo.setAuthor(sysUserService.findUserById(authorId).getNickname());
        }
        if(isBody) {
            Long bodyId = article.getBodyId();
            articleVo.setBody(findArticleBodyById(bodyId));
        }
        if(isCategory) {
            Long categoryId = article.getCategoryId();
            articleVo.setCategory(categoryService.findCategoryById(categoryId));
        }

        return articleVo;
    }

    @Autowired
    private ArticleBodyMapper articleBodyMapper;

    private ArticleBodyVo findArticleBodyById(Long bodyId) {
        ArticleBody articleBody = articleBodyMapper.selectById(bodyId);
        ArticleBodyVo articleBodyVo = new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());
        return articleBodyVo;
    }
}
